﻿

@inject IHttpService _httpService
@inject IPopupService PopupService

<MDialog @bind-Value="Dialog"
         Width="800">
    <MDCard>
        <MCardTitle Class="text-h5">
            导入抽中的用户
        </MCardTitle>
        <MCardText>
            将生成的json填入下方，我们会尝试应用到数据库
        </MCardText>
        <MCardText>
            <MTextarea Rows="5" Label="导入的Json" @bind-Value="ImportString"/>

        </MCardText>

        <MCardActions Class="pb-6 pe-6 ps-6 pt-6">
            <MSpacer></MSpacer>
            <CnGalWebSite.Components.Buttons.MasaButton Text="保存" IsAsync="true" OnClick="OnSave" Icon="mdi-check" Color="success" TextStyle />
        </MCardActions>
    </MDCard>
</MDialog>


@code {
    [CascadingParameter]
    public ErrorHandler ErrorHandler { get; set; }

    bool Dialog { get; set; }

    string ImportString { get; set; }

    public async Task OnSave()
    {
        var model = Newtonsoft.Json.JsonConvert.DeserializeObject<List<ManualLotteryModel>>(ImportString);

        foreach(var item in model)
        {
            try
            {
                var obj = await _httpService.PostAsync<ManualLotteryModel, Result>("api/lotteries/DrawLottery", item);
                //判断结果
                if (obj.Successful == false)
                {
                    await PopupService.ToastErrorAsync("抽奖失败", obj.Error);
                    //_logger.LogError("抽奖失败，{error}", obj.Error);
                }
            }
            catch (Exception ex)
            {
                await ErrorHandler.ProcessError(ex, "抽奖失败");
                //_logger.LogError(ex, "抽奖失败");
            }
        }

        await PopupService.ToastSuccessAsync("导入数据完成", "导入数据完成");

    }

    public void Refresh()
    {
        Dialog = true;
        StateHasChanged();
    }
}
